package com.sicheng.datastruct.hash;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class ThreeSum {
    public static void main(String[] args) {
        int[] nums = {-1, 3, -2};
        List<List<Integer>> lists = threeSum(nums, 0);

        assert lists != null;
        lists.forEach(System.out::println);
    }

    public static List<List<Integer>> threeSum(int[] nums, int target) {
        if (nums.length <= 2) {
            return null;
        }


        Arrays.sort(nums);
        List<List<Integer>> result = new ArrayList<>();
        List<Integer> list;

        for (int i = 0; i < nums.length - 2; i++) {
            for (int j = 0; j < nums.length - 1; j++) {
                int k = Arrays.binarySearch(nums, j + 1, nums.length, target - nums[i] - nums[j]);
                if (k > 0) {
                    list = new ArrayList<>();
                    list.add(nums[i]);
                    list.add(nums[j]);
                    list.add(nums[k]);
                    Collections.sort(list);
                    if (!result.contains(list))
                        result.add(list);
                }
            }
        }
        return result;
    }
}
